// Author: Cezary Tomczak [www.gosu.pl] [cagret#gmail]
function $(id) { return document.getElementById(id); }
var WScript = new function()
{
    this.CreateObject = function(s) {
        return new ActiveXObject(s);
    };
    this.Echo = function(s) {
        alert(s);
    };
    this.Sleep = function(s) {};
    this.Quit = function(s) { window.close(); debugger; };
};
var shell = WScript.CreateObject('WScript.Shell');
function fixPath(s) { return s.replace(/\//g, '\\'); }

var realDir = fixPath(shell.CurrentDirectory);
if (realDir.substr(realDir.length-1, 1) != '\\') {
    realDir += '\\';
}

function echo(s)
{
    var str = "";
    if (s && typeof s == "boolean") { s = s ? "true" : "false"; }
    if (s && typeof s == "object" && s.constructor != Array) { 
        if (s.toString().match(/error/i)) {
            WScript.Echo(s.toString()+"\n"+s.message);
            return;
        }
        var s2 = s;
        var ret = '';
        for (var i = 0; i < s2.length; i++) {
            ret += '['+i+'] => '+s2[i]+"\n";
        }
        WScript.Echo(ret);
        return;
    }
    if (s && typeof s == 'object' && s.constructor == Array) {
        for (var i = 0; i < s.length; ++i) {
            str += '['+i+'] => '+s[i]+'\r\n';
        }
        s = str;
    }
    WScript.Echo(s);
}
var File = new function() {
    this.fso = WScript.CreateObject('Scripting.FileSystemObject');
    this.ado = WScript.CreateObject('ADODB.Stream');
    //adModeRead  	1  	Read-only
    //adModeWrite 	2 	Write-only
    this.forReading = 1;
    this.forWriting = 2;
    this.forAppending = 8;
    this.exists = function(file) {
        return this.fso.FileExists(file);
    };
    this.create = function(file) {
        var f = this.fso.CreateTextFile(file, true);
        f.close();
    };
    this.read = function(file)
    {
        this.ado.Open();
        this.ado.CharSet = 'UTF-8';
        this.ado.LoadFromFile(file);
        var s = this.ado.ReadText();
        this.ado.Close();
        return s;
    };
    this.read_fso = function(file)
    {
        // old using FSO, but utf-8 not supported, only unicode/ascii
        var f = this.fso.OpenTextFile(file, this.forReading, false, -2); // -2 Opens the file using the system default. - required for reading NFO files
        var s = f.AtEndOfStream ? "" : f.ReadAll();
        f.close();
        return s;
    };
    this.write_binary = function(file, bytes)
    {
        this.ado.Type = 1; // adTypeBinary = 1
        this.ado.Open();
        this.ado.Write(bytes);
        this.ado.SaveToFile(file, 2); // adSaveCreateNotExist=1 , adSaveCreateOverWrite=2
        this.ado.Close();
        return;
    }
    this.write = function(file, content)
    {
        this.ado.Open();
        this.ado.CharSet = 'UTF-8';
        this.ado.WriteText(content);
        //echo(file);
        this.ado.SaveToFile(file, 2); // adSaveCreateNotExist=1 , adSaveCreateOverWrite=2
        this.ado.Close();
        return;
    };
    this.write_fso = function(file, content)
    {
        // old using FSO, but utf-8 not supported, only unicode/ascii
        var f = this.fso.OpenTextFile(file, this.forWriting, true, -2);
        f.write(content);
        f.close();
    };
    this.append = function(file, content) {
        throw 'off';
        return;
        var f = this.fso.OpenTextFile(file, this.forAppending, true, -2);
        f.write(content);
        f.close();
    };
    this.rename = function(file, newFile) {
        this.fso.MoveFile(file, newFile);
    };
    this.copy = function(file, to) {
        this.fso.CopyFile(file, to);
    };
    this.move = function(file, to) {
        this.fso.MoveFile(file, to);
    };
    this.remove = function(file) {
        this.fso.DeleteFile(file);
    };
    this.getSize = function(file) {
        var f = this.fso.GetFile(file);
        return f.Size;
    };
    this.getCreationTime = function(file) {
        var f = this.fso.GetFile(file);
        return getIsoDate(new Date(f.DateCreated));
    };
    this.getLastWriteTime = function(file, dateObj) {
        var f = this.fso.GetFile(file);
        if (dateObj) {
            return new Date(f.DateLastModified);
        } else {
            return getIsoDate(new Date(f.DateLastModified));
        }
    };
};
var Dir = new function() {
    this.fso = WScript.CreateObject("Scripting.FileSystemObject");
    this.exists = function(dir) {
        return this.fso.FolderExists(dir);
    };
    this.create = function(dir) {
        this.fso.CreateFolder(dir);
    };
    this.read = function(dir) {
        var f = this.fso.GetFolder(dir);
        var dirs = toArray(f.SubFolders);
        var files = toArray(f.Files);
        return dirs.concat(files);
    };
    this.readFolders = function(dir) {
        return toArray(this.fso.GetFolder(dir).SubFolders);
    };
    this.readFiles = function(dir) {
        return toArray(this.fso.GetFolder(dir).Files);
    };
    this.readFull = function(dir) {
        var f = this.fso.GetFolder(dir);
        var dirs = toArray(f.SubFolders);
        var files = toArray(f.Files);
        var ret = dirs;
        for (var i = 0; i < dirs.length; ++i) {
            ret = ret.concat(this.readFull(dirs[i]));
        }
        return ret.concat(files);
    };
    this.readFilesFull = function(dir) {
        var f = this.fso.GetFolder(dir);
        var dirs = toArray(f.SubFolders);
        var files = toArray(f.Files);
        var ret = [];
        for (var i = 0; i < dirs.length; ++i) {
            ret = ret.concat(this.readFilesFull(dirs[i]));
        }
        return ret.concat(files);
    };
    this.readMoviesFull = function(dir) {
        var f = this.fso.GetFolder(dir);
        var dirs = toArray(f.SubFolders);
        var files = toArray(f.Files);
        files = filterMovies(files);
        var ret = [];
        for (var i = 0; i < dirs.length; ++i) {
            ret = ret.concat(this.readMoviesFull(dirs[i]));
        }
        return ret.concat(files);
    };
    this.rename = function(dir, newDir) {
        this.fso.MoveFolder(dir, newDir);
    };
    this.copy = function(dir, to) {
        this.fso.CopyFolder(dir, to);
    };
    this.move = function(dir, to) {
        this.fso.MoveFolder(dir, to);
    };
    this.remove = function(dir, self) {
        if (typeof self == "undefined") self = true;
        if (self) {
            this.fso.DeleteFolder(dir, true);
        } else {
            var files = Dir.read(dir);
            for (var i = 0; i < files.length; ++i) {
                if (Dir.exists(files[i])) {
                    Dir.remove(files[i]);
                } else {
                    File.remove(files[i]);
                }
            }
        }
    };
    this.getCurrentFolder = function() {
        return this.fso.GetFolder(".").Path;
    };
    this.getCurrentFolderName = function() {
        return getName(this.fso.GetFolder(".").Path);
    };
    this.getSize = function(dir) {
        var f = this.fso.GetFolder(dir);
        return f.Size;
    };
    this.getCreationTime = function(dir) {
        var f = this.fso.GetFolder(dir);
        return getIsoDate(new Date(f.DateCreated));
    };
};

function getName(s)
{
    s = fixPath(s);
    s = s.cutEnd('\\');
    return s.lastIndexOf('\\') != -1 ? s.substr(s.lastIndexOf('\\')+1) : s;
}
function getDir(s)
{
    s = fixPath(s);
    if (s.match(/^[a-z]:[\\]+$/)) {
        return s;
    }
    if (s.match(is_net_top_regexp)) {
        return s;
    }
    if (s == topDirectory) {
        return s;
    }
    s = s.cutEnd('\\');
    return s.substr(0, s.lastIndexOf('\\'))+'\\';
}
function getExtension(s)
{
    s = getName(s);
    return s.lastIndexOf('.') != -1 ? s.substr(s.lastIndexOf('.')+1) : '';
}
function padZeros(s, len) {
    s = String(s);
    return "0".repeat(len-s.length)+s;
}
function getIsoDate(d) {
    var ret = "";
    ret += d.getFullYear()+"-";
    ret += padZeros(d.getMonth()+1, 2)+"-";
    ret += padZeros(d.getDate(), 2)+" ";
    ret += padZeros(d.getHours(), 2)+":";
    ret += padZeros(d.getMinutes(), 2)+":";
    ret += padZeros(d.getSeconds(), 2);
    return ret;
}

function isArray(s) {
    return s && typeof s == "object" && s.constructor == Array;
}
function toArray(o) { 
    var e = new Enumerator(o);
    var a = [];
    for (; !e.atEnd(); e.moveNext()) { a.push(String(e.item())); }
    return a;
}
function inArray(s, a)
{
    return a.contains(s);
}

Array.prototype.contains = function(s, insensi) {
    for (var i = 0; i < this.length; ++i) {
        if (insensi && typeof this[i] == 'string' && typeof s == 'string') {
            if (this[i].toLowerCase() == s.toLowerCase()) {
                return true;
            }
        } else {
            if (this[i] === s) {
                return true;
            }
        }
    }
    return false;
};
function cloneObject(obj)
{
    var newObj = (obj instanceof Array) ? [] : {};
    for (var i in obj) {
        if (obj[i] && typeof obj[i] == 'object') {
            newObj[i] = cloneObject(obj[i]);
        } else {
            newObj[i] = obj[i];
        }
    }
    return newObj;
}
Array.prototype.removeByValue = function(value) {
    var i, indexes = [];
    for (i = 0; i < this.length; ++i) { if (this[i] === value) { indexes.push(i); } }
    for (i = indexes.length - 1; i >= 0; --i) { this.splice(indexes[i], 1); }
};
Array.prototype.unique = function(insensi) {
    var ret = [];
    for (var i = 0; i < this.length; i++) {
        if (ret.contains(this[i], insensi)) {
            continue;
        } else {
            ret.push(this[i]);
        }
    }
    return ret;
};
Array.prototype.removeEmpty = function() {
    var ret = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i]) {
            ret.push(this[i]);
        }
    }
    return ret;
};
String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/g, "");
};
String.prototype.trimLeft = function() {
    return this.replace(/^\s*/g, "");
};
String.prototype.format = function() {
    if (!arguments.length) { throw "String.format() failed, no arguments passed, this = "+this; }
    var tokens = this.split("?");
    if (arguments.length != (tokens.length - 1)) {
        debug(['String.format() failed, tokens != arguments', this, arguments, tokens])
        throw "String.format() failed, tokens != arguments, this = "+this;
    }
    var s = tokens[0];
    for (var i = 0; i < arguments.length; ++i) {
        s += (arguments[i] + tokens[i + 1]);
    }
    return s;
};
String.prototype.repeat = function(n) {
    var ret = "";
    for (var i = 0; i < n; ++i) { ret += this; }
    return ret;
};
String.prototype.startsWith = function(s, insensitive) {
    return this.substr(0, s.length).toLowerCase() == s.toLowerCase();
};
String.prototype.cutStart = function(s) {
    if (this.startsWith(s)) {
        return this.substr(s.length);
    } else {
        return this;
    }
}
String.prototype.endsWith = function(s) {
    return this.substr(this.length-s.length) == s;
};
String.prototype.cutEnd = function(s) {
    if (this.endsWith(s)) {
        return this.substr(0, this.length-s.length);
    } else {
        return this;
    }
};
String.prototype.has = function(s) {
    var count = 0, index = 0;
    while ((index = this.indexOf(s, index)) != -1) {
        count++;
        index++;
    }
    return count;
};
Number.prototype.between = function(b1, b2) {
    return (this >= b1 && this <= b2);
};
function truncate(s, len)
{
    if (s.length > len) {
        return s.substr(0, len)+'...';
    }
    return s;
}
function trunc(phrase, max_words, max_len, dots)
{
   var split = phrase.split(' ');
   var ret = '';
   for (var i = 0; i < split.length; i++) {
       if (i >= max_words) {
           if (ret.length + 1 + split[i].length > max_len) {
               if (dots) {
                   ret += dots;
               }
               break;
           }
       }
       if (ret) ret += ' ';
       ret += split[i];
   }
   return ret;
}
var alpha_pattern = '[a-zA-Z\\u00A1-\\uFFFF]';
var alpha_pattern_var = '%%%%%%';
var alpha_num_pattern = '[a-zA-Z0-9\\u00A1-\\uFFFF]';
var alpha_num_space_pattern = '[a-zA-Z0-9\\u00A1-\\uFFFF\\s]';
function firstAlphaWord(s)
{
    var ret = '';
    for (var i = 0; i < s.length; i++) {
        if (s.charAt(i).match(new RegExp('^'+alpha_word_pattern+'$', 'i'))) {
            ret += s.charAt(i);
        } else {
            if (ret) {
                return ret;
            }
        }
    }
    return ret;
}
function sortNumber(a, b)
{
    return a - b;
}
function sortFilesByName(a, b)
{
    var x = getName(a).toLowerCase().replace(/[_\.,:\-]/g, ' ').replace(/\s+/g, ' ');
    var y = getName(b).toLowerCase().replace(/[_\.,:\-]/g, ' ').replace(/\s+/g, ' ');
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function sortCds(a, b)
{
    var x = a.cdnum;
    var y = b.cdnum;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function isAloneDir(dir, files)
{
    dir = dir.cutEnd('/');
    dir = dir.cutEnd('\\');
    // checks if dir contains only given files
    for (var i = 0; i < movies_tree_orig.length; i++) {
        var file = movies_tree_orig[i];
        if ( (fixPath(file).startsWith(dir+'\\') || fixPath(file).startsWith(dir+'/')) && !inArray(file, files)) {
            return false;
        }
    }
    return true;
}
function debug(s)
{
    var html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>debug</title></head><body><h1>debug</h1><pre>';
    
    html += debug_value(s, 0);

    html += '</pre></body></html>';
    var file = 'debug.html';
    File.write(file, html);
    
    WScript.Sleep(500);
    shell.Run(file);

    try { ie.Quit(); } catch(e) {}
    
    if (typeof progress_file != 'undefined' && File.exists(progress_file)) {
        File.remove(progress_file);
    }
    WScript.Quit();
}
function dbg(s)
{
    echo(debug_value(s).replace(/&nbsp;/g, ' '));
    try { ie.Quit(); } catch(e) {}
    
    if (typeof progress_file != 'undefined' && File.exists(progress_file)) {
        File.remove(progress_file);
    }
    WScript.Quit();
}
function debug_value(s, depth)
{
    if (!depth) depth = 0;
    if (typeof s == 'undefined') {
        return ' '.repeat(depth*4)+'undefined'+'\n';
    }
    if (s === null) {
        return ' '.repeat(depth*4)+'null'+'\n';
    }
    if ((typeof s == 'boolean') || (typeof s == 'object' && s.constructor == Boolean)) {
        if (typeof s == 'object') s = s.valueOf();
        s = s ? 'true' : 'false';
        return ' '.repeat(depth*4)+String(s)+'\n';
    }
    if ((typeof s == 'string') || (typeof s == 'object' && s.constructor == String)) {
        if (typeof s == 'object') s = s.valueOf();
        s = s.replace(/</g, '&lt;');
        s = s.replace(/>/g, '&gt;');
        s = s.replace(/(\r|\n|\r\n)/g, '\\n');
        if (s.length > 50) {
            s = s.replace(/\s+/g, ' ');
            s = trunc(s, 5, 500, '...');
        }
        return ' '.repeat(depth*4)+(s.length?s:'empty')+'\n';
    }
    if ((typeof s == 'number') || (typeof s == 'object' && s.constructor == Number)) {
        if (typeof s == 'object') s = s.valueOf();
        return ' '.repeat(depth*4)+String(s)+'\n';
    }

    var ret = '';

    if (depth > 5) {
        return ' '.repeat(depth*4)+'max depth 5'+'\n';
    }

    if (isArray(s)) {
        ret += ' '.repeat(depth*4)+'array'+'\n';
        for (var i = 0; i < s.length; i++) {
            ret += ' '.repeat(depth*4)+'['+i+'] ' + debug_value(s[i], depth+1).replace(/^\s+/g, '');
        }
    } else {
        ret += ' '.repeat(depth*4)+'object'+'\n';
        var isEmpty = true;
        for (var i in s) {
            isEmpty = false;
            if (s[i].constructor == Function) {
                continue;
            }
            ret += ' '.repeat(depth*4)+'['+i+'] ' + debug_value(s[i], depth+1).replace(/^\s+/g, '');
        }
        if (isEmpty) {
            ret = ret.cutEnd('\n');
            ret += ' (empty)\n';
        }
    }

    return ret;
}
var debug_push_arr = [];
function debug_push(v)
{
    debug_push_arr.push(v);
}
function time_micro()
{
    var micro = new String(new Date().getTime());
    micro = micro.substr(0, micro.length-3) + '.' + micro.substr(micro.length-3, 3);
    return parseFloat(micro);
}
function time_start()
{
    return time_micro();
}
function time_end(start)
{
    return time_round(time_micro() - start);
}
function time_round(time)
{
    time = Math.round(time * 100) / 100;
    if (time === 0) { time = 0.01; }
    return time;
}
var times = [];
var time1 = null;
function time(msg)
{
    if (msg) {
        times.push(msg);
        time1 = time_start();
    } else {
        if (!time) throw 'time is null';
        times.push(time_end(time1)+': '+times.pop())
        time1 = null;
    }
}

if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(typeof value.length==='number'&&!value.propertyIsEnumerable('length')){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}})();